<template>
  <div>
    <items-head title="联系人列表" />
    <div class="wrap">
      <van-address-list v-model="chosenAddressId"
                        :list="list"
                        default-tag-text="默认"
                        @add="onAdd"
                        @edit="onEdit"
                        @select="switchAddress" />
    </div>
  </div>
</template>

<script>
import ItemsHead from 'components/ItemsHead'
import { fetchContacts } from 'api'
import { getToken } from 'utils'
export default {
  name: 'contactsList',
  data () {
    return {
      chosenAddressId: '1',
      list: []
    }
  },
  created () {
    this.fetchContacts()
  },
  beforeRouteEnter (to, from, next) {
    localStorage.setItem('from', from.path)
    next()
  },
  methods: {
    switchAddress (contact, index) {
      const from = localStorage.getItem('from')
      if (from === '/confirmorder') {
        this.$router.push({
          path: from,
          query: {
            id: contact.id
          }
        })
      } else if (from === '/addcont') {
        this.$router.push({
          path: '/confirmorder',
          query: {
            id: contact.id
          }
        })
      } else {
        this.$router.push({
          path: '/confirmorder',
          query: {
            id: contact.id
          }
        })
      }
    },
    fetchContacts () {
      fetchContacts({ token: getToken() }).then(res => {
        if (res.data.code === 0) {
          const params = res.data.data.result
          params.forEach(item => {
            const { id, mobile, linkMan, address, isDefault } = item
            item = {
              id,
              name: linkMan,
              tel: mobile,
              address,
              isDefault
            }
            this.list.push(item)
          })
          const contactId = this.list.find(item => item.isDefault)
          // 如果有默认联系人 选中id 就是默认联系人
          if (contactId) {
            this.chosenAddressId = contactId.id
          } else {
            this.chosenAddressId = this.list[0].id
          }
        }
      })
    },
    onAdd () {
      this.$router.push('/addcont')
    },
    onEdit (contact) {
      this.$router.push({
        path: '/updatecont',
        query: {
          id: contact.id
        }
      })
    }
  },
  components: {
    ItemsHead
  }
}
</script>

<style lang="scss" scoped>
.wrap {
  padding: 46px 0 50px;
}
</style>
